/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.dao;

import han.bifang.common.entity.EntityConstants;
import han.bifang.common.entity.SoaService;
import han.bifang.common.entity.SoaUser;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;
import han.bifang.common.persist.dao.DaoManager;
import han.bifang.common.persist.tx.Tx;
import han.bifang.common.persist.tx.TxManager;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class AuthDao {

	public static boolean checkPermission(String loginName, String serviceCode)
			throws BifangException {
		Tx tx = null;
		boolean ret = false;
		try {
			tx = TxManager.start();
			
			String resourceId  = null;
			String hql =  "select s.id from SoaService s where s.serviceCode = ? ";

			List<String> ses = (List<String>)DaoManager.getDao().find(hql, serviceCode);
			if(ses.size() > 0 ){
				String id = ses.get(0);
				hql = "select s.id from SoaResource s where s.entityId = ? and s.type = ?";
				List<String> o = (List<String>)DaoManager.getDao().find(hql,
						new Object[] { id, EntityConstants.RESOURCE_LOCAL_SERVICE });
				if(o.size() > 0){
					resourceId = o.get(0);
				}				
			}else{
				hql = "select s.id from SoaMappingService s where s.localCode = ? ";

				ses = DaoManager.getDao().find(hql, serviceCode);
				if(ses.size() > 0){
					String id = ses.get(0);
					hql = "select s.id from SoaResource s where s.entityId = ? and s.type = ?";
					List<String> o = (List<String>)DaoManager.getDao().find(hql,
							new Object[] { id, EntityConstants.RESOURCE_REMOTE_SERVICE });
					if(o.size() > 0){
						resourceId = o.get(0);
					}
				}else{
					throw new BifangException(BifangErrorCode.SERVICE_CODE_NOT_EXISTS_ERROR,"no such service");
				}
			}
			
				
			hql = "from SoaUser s where s.loginName = ?";
			List<SoaUser> users = DaoManager.getDao().find(hql, loginName);
			SoaUser u = users.get(0);
			if (u != null) {
				//first find groups
				hql = "select r.compId.usergroupId  from SoaUsergroupUserRel r where r.compId.userId = ?";
				List<String> gIds = DaoManager.getDao().find(hql, u.getId());
				
				//find target roles
				hql = "select r.compId.roleId  from SoaRoleResRel r where r.compId.resId = ?";
				List<String> rIds = DaoManager.getDao().find(hql, resourceId);

				//find user's roles
				StringBuffer sb = new StringBuffer();
				for (String id : gIds) {
					sb.append("'" + id + "',");
				}
				String tmp = sb.toString();
				tmp = tmp.substring(0, tmp.length() - 1);
				hql = "select distinct r.compId.roleId  from  SoaUsergroupRoleRel r where r.compId.usergroupId in "
						+ "(" + tmp + ")";
				List<String> rrIds = DaoManager.getDao().find(hql);
				//check if user has target role.
				for (String id : rIds) {
					if (rrIds.contains(id)) {
						ret = true;
						break;
					}
				}

			}
			tx.commit();
			return ret;
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(BusBindingDao.class);
			logger.error("AuthDao.checkPermission()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"checkPermission() error", e);
		} finally {
			tx.end();
		}

	}
}
